package com.thingple.usb;

import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Window;

import androidx.appcompat.app.AppCompatActivity;

import com.thingple.usb.manager.UsbManagerWrapper;
import com.thingple.util.Alert;

public class UsbAttachedActivity extends AppCompatActivity {

    private static final String TAG = UsbAttachedActivity.class.getName();

    protected UsbDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_usb_attached);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        Alert.ctx = this;

        initDialog();

        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            Log.d(TAG, "close");
            finish();
        }, 1500);
    }

    private void initDialog() {
        dialog = new UsbDialog(this, v -> finish());
        dialog.setContent("检测到USB设备接入");
        dialog.show();
        init();
    }

    private void init() {
        UsbManager manager = getSystemService(UsbManager.class);
        if (manager == null) {
            return;
        }
        UsbAccessory[] accessories = manager.getAccessoryList();
        if (accessories == null || accessories.length == 0) {
            return;
        }
        UsbAccessory accessory = accessories[0];
        if (accessory == null) {
            return;
        }
        if (!manager.hasPermission(accessory)) {
            Alert.msg("申请权限");
            UsbManagerWrapper.requestPermission(this, manager, accessory);
        }
    }

    @Override
    protected void onDestroy() {
        if (dialog != null) {
            dialog.onDestroy();
        }
        super.onDestroy();
    }
}